<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title th:replace="common/base::pagetitle"></title>
    <link th:replace="common/base::static"/>
</head>
<body style="background-color: #f2f2f2;">

<div id="kPage" class="layui-fluid" style="padding: 0">
    <div class="layui-row">
        <div class="layui-col-md12" id="kMainContentCol">
            <div class="layui-fluid kvf-fluid-padding15">
                <div class="layui-card">
                    <form>
                        <div class="layui-form layui-card-header kvf-card-header-auto">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">模型名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="modelName" placeholder="请输入模型名称" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">流程名称</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="processName" placeholder="请输入流程名称" autocomplete="off" class="layui-input">
                                    </div>
                                </div>

                                <div class="layui-inline">
                                    <button class="layui-btn " lay-submit="" lay-filter="kTableSearchFilter">
                                        <i class="layui-icon layui-icon-search"></i>
                                    </button>
                                    <button class="layui-btn " type="reset" data-event="refresh">
                                        <i class="layui-icon layui-icon-refresh-1"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>

                    <div class="layui-card-body">
                        <table id="kContentTable" lay-filter="kContentTable"></table>
                    </div>
                </div>

                <!-- 创建模型模板 -->
                <!--<div class="layui-container" style="display: none; width: 500px" id="modelLayout">
                    <div class="layui-form" style="margin-top: 30px;">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">模型名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="modelName" placeholder="请输入模型名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">模型KEY</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="modelKey" placeholder="请输入模型KEY" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">模型描述</label>
                            <div class="layui-input-block">
                                <textarea name="description" placeholder="请输入模型描述" class="layui-textarea"></textarea>
                            </div>
                        </div>
                    </div>
                </div>-->

                <!--  导入流程模型弹出层 -->
                <div class="layui-container" style="display: none; width: 300px" id="uploadLayout">
                    <div class="layui-upload" style="margin-top: 30px;">
                        <div class="layui-upload-drag" id="pick">
                            <i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>
                            <div class="layui-hide" id="uploadDemoView">
                                <hr>
                                <img src="" alt="上传成功后渲染" style="max-width: 196px">
                            </div>
                        </div>
                        <div class="layui-col-md12 layui-hide">
                            <button type="button" class="layui-btn layui-btn-sm" id="uploadAndImport">上传并导入</button>
                        </div>

                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script th:replace="common/base::context"></script>
<script th:replace="common/base::mainjs"></script>

<!--头部工具栏模板-->
<script type="text/html" id="headToolbarTpl">
    <button class="layui-btn layui-btn-sm " lay-event="add">创建</button>
    <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="batchdel">删除</button>
    <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="suspend">挂起</button>
    <button class="layui-btn layui-btn-sm " lay-event="activate">激活</button>
   <!-- <button class="layui-btn layui-btn-sm layui-bg-blue" lay-event="export">导出</button>
    <button class="layui-btn layui-btn-sm layui-bg-orange" lay-event="import">导入</button>-->
    <button class="layui-btn layui-btn-sm layui-bg-blue" lay-event="setting">配置</button>
</script>

<!--表格行工具栏模板-->
<script type="text/html" id="rowToolbarTpl">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>设计</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="push"><i class="layui-icon layui-icon-release"></i>发布</a>
    <a class="layui-btn layui-btn-xs" lay-event="start"><i class="layui-icon layui-icon-play"></i>启动</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<!--表格列格式化模板 start-->
<script type="text/html" id="pushStatusTpl">
    {{#  if(d.deploymentId){ }}
    <span class="layui-badge layui-bg-red">已发布</span>
    {{# } else { }}
    <span class="layui-badge layui-bg-blue">未发布</span>
    {{# } }}
</script>
<script type="text/html" id="statusTpl">
    {{#  if(d.processSuspended == true){ }}
    <span class="layui-badge layui-bg-black">挂起</span>
    {{# } else if(d.processSuspended == false) { }}
    <span class="layui-badge layui-bg-green">激活</span>
    {{# } else { }}
<!--    <span class="layui-badge layui-bg-blue"></span>-->
    {{# } }}
</script>
<!--表格列格式化模板 end-->

<script type="text/javascript" th:inline="javascript">
    layui.use(['element', 'form', 'layer', 'table', 'laydate', 'upload'], function () {
        var elemet = layui.element, form = layui.form, layer = layui.layer, table = layui.table, laydate = layui.laydate;
        var upload = layui.upload;
        var tableId = 'kContentTable';
        var area = ['449px', '95%'];

        // 实例化table
        var tableIns = table.render($.extend(config.layui.table, {
            elem: '#' + tableId
            ,url: BASE_WEB + 'workflow/process/list' // 数据接口
            ,toolbar: '#headToolbarTpl'
            ,cols: [[ //表头
                {type:'checkbox', fixed: 'left'}
                // ,{field: 'id', title: '模型ID', width: 130}
                ,{field: 'name', title: '流程模型名称', width: 200}
                ,{field: 'processName', title: '发布流程名称'}
                ,{field: 'deploymentId', title: '发布状态', width: 90, align: 'center', templet: '#pushStatusTpl'}
                ,{field: 'processSuspended', title: '状态', width: 70, align: 'center', templet: '#statusTpl'}
                ,{field: 'version', title: '版本', width: 60, align: 'center', templet: '<div><span class="layui-badge layui-bg-gray">{{d.version}}</span></div>'}
                ,{field: 'createTime', title: '创建时间', width: 180, templet: formatCreateTime}
                ,{field: 'lastUpdateTime', title: '最后更新', width: 180, templet: formatLastUpdateTime}
                ,{field: '', title: '操作', width: 300, fixed: 'right', templet: '#rowToolbarTpl'}
            ]]
        }));

        // 监听表格头部事件
        table.on('toolbar(' + tableId + ')', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var checkData = checkStatus.data; // 得到选中的数据
            switch(obj.event) {
                case 'add':
                    layer.open({
                        type: 2
                        ,title: '创建模型'
                        ,content: BASE_WEB + 'workflow/create/index'
                        ,maxmin: false
                        ,area: area   // 宽高
                        ,btn: ['确定', '取消']
                        ,yes: function (index, layero) {
                            //点击确认触发 iframe 内容中的按钮提交
                            var submit = layero.find('iframe').contents().find("#kFormSubmit");
                            submit.click();
                        }
                    });
                    break;
                case 'batchdel':
                    if(checkData.length === 0){
                        return kvfKit.warningMsg('请选择数据');
                    }
                    layer.confirm('确定删除吗？', function(index) {

                        var ids = [];
                        $.each(checkData, function(i, n){
                            ids[i] = n.id;
                        });

                        //执行 Ajax 后重载
                        $.ajax({
                            type: req.type.post,
                            url: BASE_WEB + 'workflow/delete/batch',
                            data: {modelIds: ids.toString()},
                            success: function (r) {
                                if (r.code === req.status.ok) {
                                    table.reload(tableId);
                                    kvfKit.sucessMsg('已删除');
                                } else {
                                    kvfKit.errorMsg(r.msg);
                                }
                            }
                        });

                    });
                    break;
                case 'suspend':
                    if(checkData.length === 0){
                        return kvfKit.warningMsg('请选择数据');
                    }
                    layer.confirm('挂起流程流程将不能使用，确定要挂起选择的流程吗？', function(index) {

                        var ids = [];
                        $.each(checkData, function(i, n){
                            if (n.deploymentId) {
                                ids[i] = n.deploymentId;
                            }
                        });

                        if (ids.length === 0) {
                            kvfKit.warningMsg('只能对已发布及激活的流程进行挂起');
                            return false;
                        }

                        //执行 Ajax 后重载
                        $.ajax({
                            type: req.type.post,
                            url: BASE_WEB + 'workflow/suspend/process',
                            data: {deploymentIds: ids.toString()},
                            success: function (r) {
                                if (r.code === req.status.ok) {
                                    table.reload(tableId);
                                    kvfKit.sucessMsg('已挂起');
                                } else {
                                    kvfKit.errorMsg(r.msg);
                                }
                            }
                        });

                    });
                    break;
                case 'activate':
                    if(checkData.length === 0){
                        return kvfKit.warningMsg('请选择数据');
                    }
                    layer.confirm('确定激活选择的流程吗？', function(index) {

                        var ids = [];
                        $.each(checkData, function(i, n){
                            if (n.deploymentId) {
                                ids[i] = n.deploymentId;
                            }
                        });

                        if (ids.length === 0) {
                            kvfKit.warningMsg('只能对已发布及挂起的流程进行激活');
                            return false;
                        }

                        //执行 Ajax 后重载
                        $.ajax({
                            type: req.type.post,
                            url: BASE_WEB + 'workflow/activate/process',
                            data: {deploymentIds: ids.toString()},
                            success: function (r) {
                                if (r.code === req.status.ok) {
                                    table.reload(tableId);
                                    kvfKit.sucessMsg('已激活');
                                } else {
                                    kvfKit.errorMsg(r.msg);
                                }
                            }
                        });

                    });
                    break;
                case 'export':
                    if(checkData.length === 0){
                        return kvfKit.warningMsg('请选择数据');
                    }

                    var ids = [];
                    $.each(checkData, function(i, n){
                        ids[i] = n.id;
                    });
                    window.open(BASE_WEB + 'workflow/export/batch?modelIds=' + ids);
                    break;
                case 'import':
                    layer.open({
                        type: 1,
                        title: '选择需要导入的流程模型JSON文件',
                        resize: true,
                        fixed: true,
                        shadeClose: true,
                        shade: 0.1,
                        scrollbar: false,
                        area: ['435px', '310px'],
                        content: $('#uploadLayout'),
                        btn: ['导入'],
                        yes: function(index, layero) {
                            $('#uploadAndImport').click();
                        }

                    });
                    break;
                case 'setting':
                    if(checkData.length === 0){
                        return kvfKit.warningMsg('请选择数据');
                    }
                    if(checkData.length > 1){
                        return kvfKit.warningMsg('只允许同时配置一个');
                    }
                    idx = layer.open({
                        type: 2
                        ,title: '流程模型配置'
                        ,content: BASE_WEB + 'workflow/setting?modelId=' + checkData[0].id
                        ,maxmin: true
                        ,area: ['574px', '95%']   // 宽高
                        ,btn: ['确定', '取消']
                        ,yes: function(index, layero){
                            //点击确认触发 iframe 内容中的按钮提交
                            var submit = layero.find('iframe').contents().find("#kFormSubmit");
                            submit.click();
                        }
                    });
                    // layer.full(idx);
                    break;
            }
        });

        // 表格行按钮 监听事件
        table.on('tool(' + tableId + ')', function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if (layEvent === 'edit') {
                var idx = layer.open({
                    type: 2
                    ,title: '在线流程设计器'
                    ,content: BASE_WEB + 'workflow/editor?modelId=' + data.id
                    ,maxmin: false
                    ,area: area   // 宽高
                    ,cancel: function (index) {
                        layer.confirm('关闭前请确保设计保存了没有，确认关闭?', function (idx) {
                            layer.close(index);
                            layer.close(idx);
                            table.reload(tableId);
                        });
                        return false;
                    }
                });
                layer.full(idx);
            }
            if (layEvent === 'del') {
                layer.confirm('确定删除吗？', function(index) {
                    //执行 Ajax 后重载
                    $.ajax({
                        type: req.type.post,
                        url: BASE_WEB + 'workflow/delete/' + data.id,
                        async: false,
                        success: function (r) {
                            if (r.code === req.status.ok) {
                                table.reload(tableId);
                                kvfKit.sucessMsg('已删除');
                            } else {
                                kvfKit.errorMsg(r.msg);
                            }
                        }
                    });
                });
            }
            if (layEvent === 'push') {
                layer.confirm('确定发布此流程吗？', function (index) {
                    kvfKit.aPost(BASE_WEB + 'workflow/deploy/' + data.id, {}, function (r) {
                        if (r.code === req.status.ok) {
                            kvfKit.sucessMsg('发布成功');
                            table.reload(tableId);
                        } else {
                            kvfKit.errorMsg(r.msg);
                        }
                    });
                });
            }
            if (layEvent === 'start') {
                if (!data.deploymentId) {
                    kvfKit.warningMsg("该流程未发布，不能启动");
                    return false;
                }
                kvfKit.aGet(
                    BASE_WEB + 'workflow/process/{deploymentId}/start/test'.replace("{deploymentId}", data.deploymentId),
                    function (r) {
                        if (r.code === req.status.ok) {
                            idx = layer.open({
                                type: 2
                                ,title: data.processName
                                ,content: BASE_WEB + 'workflow/task/{taskId}/form'.replace('{taskId}', r.data)
                                ,maxmin: false
                                ,area: area   // 宽高
                            });
                            layer.full(idx);
                        } else {
                            kvfKit.errorMsg(r.msg);
                        }
                    }
                )
            }
        });

        // 监听查询
        form.on('submit(kTableSearchFilter)', function (obj) {
            renderTableData(obj.field);
            return false;
        });

        var active = {
            refresh: function () {
                var $form = $('form');
                $form[0].reset();
                renderTableData(kvfKit.getFormJson($form));
            }
        };

        kvfKit.activeInit(active);

        function renderTableData(params) {
            params = params ? params : {};

            tableIns.reload({
                where: params,
                page: {curr: 1}
            });
        }

        // 绑定监听回车事件
        kvfKit.bindEnterEventForLayuiForm();

        function formatCreateTime(d) {
            return new Date(d.createTime).format("yyyy-MM-dd hh:mm:ss")
        }

        function formatLastUpdateTime(d) {
            return new Date(d.lastUpdateTime).format("yyyy-MM-dd hh:mm:ss")
        }

        // 选完文件后不自动上传
        //拖拽上传
        upload.render({
            elem: '#pick'
            ,url: BASE_WEB + 'workflow/import/batch'
            ,auto: false
            ,accept: 'file'
            ,multiple: false
            ,bindAction: '#uploadAndImport'
            ,done: function(r){
                if (r.code === req.status.ok) {
                    kvfKit.sucessMsg('导入成功');
                    table.reload(tableId);
                } else {
                    kvfKit.errorMsg('导入失败：' + r.msg)
                }
            }
        });

        // 奇葩.bug
        // 本地启动访问是没有问题的，但是使用域名访问那个地址就会出奇葩~~
        // TODO: 为了解决第一次请求【http://kvfadmin.kalvinbg.cn/static/workflow/editor-app/editor.html】会强制添加前缀【http://tieba.baidu.com/_PXRD_5eb7340e109d398635084】的奇葩BUG
        var freakUrl = BASE_WEB + 'static/workflow/editor-app/editor.html';
        $.ajax( {
            url: freakUrl,
            type: req.type.get,
            success: function(r) {
                error('1.为了解决第一次请求【http://kvfadmin.kalvinbg.cn/static/workflow/editor-app/editor.html】会强制添加前缀【http://tieba.baidu.com/_PXRD_5eb7340e109d398635084】的奇葩BUG');
            },
            error: function (xhr, status, err) {
                $.ajax( {
                    url: freakUrl,
                    type: req.type.get,
                    success: function(r) {
                        error('2.为了解决第一次请求【http://kvfadmin.kalvinbg.cn/static/workflow/editor-app/editor.html】会强制添加前缀【http://tieba.baidu.com/_PXRD_5eb7340e109d398635084】的奇葩BUG');
                    },
                });
            }
        });

    });
</script>

</body>
</html>